<?php

namespace frontend\modules\dynamic\models;

use common\models\dynamic\Dynamic;
use common\models\dynamic\DynamicComment;
use common\models\mongo\DynamicMess;
use Yii;
use yii\base\Model;
use common\models\dynamic\DynamicLikeLog;
use common\exceptions\ModelHttpException;

class DynamicLikeForm extends Model {

    /**
     * @name $user_id
     * @var integer 用户UID
     */
    public $user_id;

    /**
     * @name $dynamic_id
     * @var integer 动态ID
     */
    public $dynamic_id;

    /**
     * @name $comment_id
     * @var integer 动态评论ID
     */
    public $comment_id = 0;

    /**
     * @return array validation rules
     */
    public function rules() {
        return [
            [['user_id', 'dynamic_id', 'comment_id'], 'integer'],
            [['dynamic_id'], 'required'],
        ];
    }

    private $passiveUserId;

    /**
     * 保存动态信息（发布&修改）
     * @param [type] $data
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            throw new ModelHttpException('点赞操作参数校验失败', $this->getFirstErrors());
        }

        $model = DynamicLikeLog::findOrNew($this->attributes);
        if ($model->isNewRecord) {
            if ($model->save()) {
                $this->pushQueue();
            }
            return true;
        }
        return !$model->delete();
    }

    protected function pushQueue() {
        //点赞推送
        if (YII_ENV_DEV) {
            return;
        }
        $this->pushLikeQueue();
    }

    /**
     * 点赞推送消息
     * [
     *   active_input = [
     *      'user_id'
     *   ],
     *   passive_input = [
     *      user_id
     *      dynamic_id,
     *      comment_id
     *   ]
     * ]
     */
    private function pushLikeQueue() {

        if ($this->comment_id) {
            $comment = DynamicComment::findx($this->dynamic)
                ->where([
                    'id' => $this->comment_id
                ]);
            $this->passiveUserId = $comment->user_id;
        } else {
            $dynamic = Dynamic::findOne($this->dynamic_id);
            $this->passiveUserId = $dynamic->user_id;
        }

        Yii::$app->queue->push(new \common\jobs\DynamicMessageJob([
            'active_input' => [
                'user_id' => $this->user_id,
            ],
            'passive_input' => [
                [
                    'user_id' => $this->passiveUserId,
                    'comment_id' => $this->comment_id,
                    'dynamic_id' => $this->dynamic_id
                ]
            ],
            'mess_type' => DynamicMess::MESS_TYPE_LIKE
        ]));
    }

}
